﻿using System;
using System.Text;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Threading;

namespace Terrain
{
	internal class Timer
	{
		[DllImport("Kernel32.dll")]
		private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);

		[DllImport("Kernel32.dll")]
		private static extern bool QueryPerformanceFrequency(out long lpFrequency);

		[DllImport("Kernel32.dll")]
		public static extern uint GetTickCount();

		private long timeTicks;
		private long freq;

		private double last, current;
		private double dt;

		public delegate double DGetTime();
		public DGetTime GetTime;

		public Timer()
		{
			if (QueryPerformanceFrequency(out freq)) GetTime = new DGetTime(GetTime_precise);
			else GetTime = new DGetTime(GetTime_simple);

			last = GetTime();
		}

		private double GetTime_precise()
		{
			QueryPerformanceCounter(out timeTicks);
			return (double)(timeTicks / (double)freq);
		}

		private double GetTime_simple() { return GetTickCount() / 1000.0; }

		public double GetTimeInterval()
		{
			current = GetTime();
			dt = (current - last);
			last = current;
			return dt;
		}
	}
}